from ftplib import FTP
from ftplib import error_perm


class FTP_OP():
    def __init__(self, host, username, password, port):
        self.host = host
        self.username = username
        self.password = password
        self.port = port

    def ftp_connect(self):
        self.ftp = FTP()
        self.ftp.encoding = 'UTF-8'  # 适应中文编码
        try:
            # self.ftp.set_debuglevel(2)  # 调试级别
            self.ftp.connect(self.host, self.port)
            self.ftp.login(self.username, self.password)
            self.ftp.set_pasv(False)  # 设置被动模式
        except error_perm:
            print('[ERROR]: user authentication failed.')
            return -1
        except Exception as e:
            print('[ERROR]: ftp connect failed. %s' % e)
            return -1
        print('***ftp success connected.***')

    def download_file(self, ftp_file, local_file):
        # 从ftp服务器上下载文件到本地
        # ftp_file: 远端要下载的文件
        # local_file: 保存到本地文件
        bufsize = 1024
        with open(local_file, 'wb') as f:
            self.ftp.retrbinary("RETR %s" % ftp_file, f.write, bufsize)

    def upload_file(self, ftp_file, local_file):
        # 上传本地文件至ftp服务器
        # ftp_file:保存至ftp的文件名
        # local_file：本地文件
        bufsize = 1024
        with open(local_file, 'rb') as f:
            self.ftp.storbinary("STOR %s" % ftp_file, f, bufsize)

    def ftp_quit(self):
        # 退出ftp
        self.ftp.quit()


if __name__ == '__main__':
    ftp = FTP_OP("192.168.15.10", 'user1', 'yz123456', 21)
    ftp.ftp_connect()

    ftp_filename1 = 'test/log_api//test.log'
    ftp_filename2 = 'test/log_api//case_runned.txt'
    ftp_filename3 = 'test/log_api//test_pm.log'

    local_filename1 = 'D:\\log_aip\\Results\\test.log'
    local_filename2 = 'D:\\log_aip\\Results\\case_runned.txt'
    local_filename3 = 'D:\\log_aip\\Results\\test_pm.log'

    # 下载文件至本地
    ftp.download_file(ftp_filename1, local_filename1)
    ftp.download_file(ftp_filename2, local_filename2)
    ftp.download_file(ftp_filename3, local_filename3)


    ftp.ftp_quit()
